package com.syf.kit.core.dao.impl;

import com.syf.kit.core.dao.SyfRdsDaoUtil;
import com.syf.kit.core.dao.SyfRdsDaoUtilFactory;
import com.syf.kit.core.dao.mapper.MapperType;
import com.syf.kit.core.ds.impl.SyfDataSource;
import com.syf.kit.enums.DataSourceType;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.util.HashMap;
import java.util.Map;

public class SyfMultipleRdsDaoUtilFactory implements SyfRdsDaoUtilFactory {

    private SyfDataSource syfDataSource;

    /***
     * mybatis 事务工厂
     * */
    private TransactionFactory dbTxFactory;

    private Map<String, SyfSimpleRdsDaoUtilFactory> daoUtilsFactoryMap;

    private boolean autocommit;

    public SyfMultipleRdsDaoUtilFactory(SyfDataSource syfDataSource, boolean autocommit, MapperType mapperType) {
        this(syfDataSource, new JdbcTransactionFactory(), autocommit, mapperType);
    }

    public SyfMultipleRdsDaoUtilFactory(SyfDataSource syfDataSource, TransactionFactory dbTxFactory, boolean autocommit, MapperType mapperType) {
        this.syfDataSource = syfDataSource;
        this.dbTxFactory = dbTxFactory;
        this.autocommit = autocommit;
        this.daoUtilsFactoryMap = new HashMap<>();
        for (String dsName : syfDataSource.getDataSourceNameSet()) {
            daoUtilsFactoryMap.put(dsName, new SyfSimpleRdsDaoUtilFactory(syfDataSource, dbTxFactory, autocommit, mapperType));
        }
    }

    @Override
    public SyfRdsDaoUtil buildSyfRdsDaoUtil() {
        if (!DataSourceType.MULTIPLE.equals(syfDataSource.getDsType())) {
            throw new RuntimeException("非法调用，此处必须传入：SyfMultipleDataSource");
        }

        Map<String, SyfSimpleRdsDaoUtil> rdsDaoUtilMap = new HashMap<>();
        for (Map.Entry<String, SyfSimpleRdsDaoUtilFactory> entry : daoUtilsFactoryMap.entrySet()) {
            rdsDaoUtilMap.put(entry.getKey(), (SyfSimpleRdsDaoUtil) entry.getValue().buildSyfRdsDaoUtil());
        }

        return new SyfMultipleRdsDaoUtil(rdsDaoUtilMap);
    }
}
